
package com.onlineMIS.action.headQ.inventoryFlow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.onlineMIS.ORM.DAO.JspLoadResult;
import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.chainS.ChainUtility;
import com.onlineMIS.ORM.DAO.headQ.inventoryFlow.HeadqInventoryFlowService;
import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInventoryFlowOrder;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInvenTraceInfoVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryFlowOrder;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HqInventoryChangeDetailsVO;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.filter.SystemParm;
import com.opensymphony.xwork2.ActionContext;

/**
 * action to
 * 
 * @author fredo
 *
 */
@SuppressWarnings("serial")
public class HeadqInventoryFlowJSPAction extends HeadqInventoryFlowAction {
	private final String CHAIN_INVENTORY_REPORT_TEMPLATENAME = "HqInventoryReportTemplate.xls";
	private final String INVENTORY_CHANGE_REPORT_TEMPLATENAME = "HqInventoryChangeReportTemplate.xls";
	private final String INVENTORY_CHANGE_REPORT_DETAILS_TEMPLATENAME = "HqInventoryChangeReportDetailsTemplate.xls";
	private final String CHAIN_INVENTORY_REPORT_NAME = "KuCunBiao.xls";
	private final String hqInventoryStockTemplate= "InventoryStockHistory.xls";

	@Autowired
	private HeadqInventoryFlowService flowService;

	


	/**
	 * action to re-calculate (重新计算) the inventory order such as quantity (刷新库存)
	 * 
	 * @return
	 */
	public String calculateInventoryOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "calculateInventoryOrder ");

		Response response = flowService.calculateInventoryOrder(formBean.getFlowOrder());

		if (response.getReturnCode() != Response.SUCCESS) {
			addActionError(response.getMessage());
		} else {
			HeadqInventoryFlowOrder flowOrder = (HeadqInventoryFlowOrder) response.getReturnValue();

			flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, flowOrder);
		}

		return "editInventoryOrder";
	}

	/**
	 * 一键修复库存，只会核对单据上的物品的库存
	 * 
	 * @return
	 */
	public String oneKeyAdjustInventory() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "oneKeyAdjustInventory ");

		Response response = new Response();
		try {
			response = flowService.adjustInventory(formBean.getFlowOrder(), loginUser,formBean.getJsons());
			if (response.getReturnCode() == response.FAIL) {
				addActionError(response.getMessage());			
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
				return loadOrder();
			}else {
				addActionMessage(response.getMessage());
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			e.printStackTrace();
			loggerLocal.error("HeadqInventoryFlowAction.oneKeyAdjustInventory: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}
		return preCreateInventoryOrder();
	}

	/**
	 * 此单据应该是连锁店的实际库存,此功能将使用此单据完全取代电脑库存 扎账
	 * 
	 * @return
	 */
	public String oneKeyClearAndAdjustInventory() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "oneKeyClearAndAdjustInventory ");

		Response response = new Response();
		try {
			response = flowService.clearAndadjustInventory(formBean.getFlowOrder(), loginUser,formBean.getJsons());
			if (response.getReturnCode() == response.FAIL) {		
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
				return loadOrder();
			}else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.oneKeyClearAndAdjustInventory: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}

		return preCreateInventoryOrder();
	}

	/**
	 * 生成最终报表 action to generate the inventory report
	 * 
	 * @return
	 */
	public String genInventoryReport() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "genInventoryReport ");

		Response response = new Response();
		try {
			response = flowService.genInventoryReport(formBean.getFlowOrder(), formBean.getInventory(),formBean.getJsons(), loginUser);
			if (response.getReturnCode() == response.FAIL) {		
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
				return loadOrder();
			}else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("ChainInventoryFlowAction.genInventoryReport: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}

		return preCreateInventoryOrder();
	}

	/**
	 * 下载条码 action to download the barcodes
	 * 
	 * @return
	 */
	public String getBarcodeFile() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "getBarcodeFile ");
		InputStream fileStream = null;
		Date date = new Date();
		formBean.setFileName("barcode.txt");

		File barcodeFile = new File(SystemParm.getParm("BARCODE_DOWNLOAD_PATH"));
		if (!barcodeFile.exists())
			fileStream = flowService.genBarcodeFile();
		else {
			try {
				fileStream = new FileInputStream(barcodeFile);
			} catch (FileNotFoundException e) {
				loggerLocal.error(e);
				fileStream = flowService.genBarcodeFile();
			}
		}

		formBean.setFileStream(fileStream);

		return "download";
	}

	private String postSubmitFlowOrder(boolean toFinalize,HeadqInventoryFlowFormBean formBean,UserInfor loginUser) {
		// clear the data
		int orderId = formBean.getFlowOrder().getId();
		int orderType = 0;
		HeadqInventoryFlowOrder order = new HeadqInventoryFlowOrder();
		if (orderId == Common_util.ALL_RECORD_NEW) {
			order = formBean.getFlowOrder();
			order = formBean.getFlowOrder();
			orderType = formBean.getFlowOrder().getType();
			order = flowService.excludeUnqualified(order);
						
		}else if (orderId != 0 && formBean.getFlowOrder().getStatus() == BaseOrder.STATUS_DRAFT) {
			order = formBean.getFlowOrder();
			orderType = formBean.getFlowOrder().getType();
			order = flowService.excludeUnqualified(order);
		}else if (orderId != 0 && formBean.getFlowOrder().getStatus() == BaseOrder.STATUS_COMPLETE) {
			return loadOrder();
		}else {
			order = flowService.getOrderById(orderId, loginUser);
			orderType = order.getType();
		}
		
		if (orderType == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
			formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.OVER_FLOW_ORDER);
			return preCreateOverflowOrder(formBean);
		} else if (orderType == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {
			formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.FLOW_LOSS_ORDER);			
			return preCreateOverflowOrder(formBean);
		} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER)
			return preCreateInventoryOrder();
		else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
			return preCreateInventoryTransferOrder();
		}else
			return ERROR;
	}

	/**
	 * go to 报溢单 (overflow order) 报溢单
	 */
	public String preCreateOverflowOrder(HeadqInventoryFlowFormBean formBean) {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "preCreateOverflowOrder");

		flowService.prepareCreateOrderUI(formBean, uiBean, loginUser);

		ChainUtility.calculateParam(formBean, formBean.getFlowOrder());

		return "editFlowOrder";
	}

	/**
	 * go to create 库存单 (inventory order)
	 * 
	 * @return
	 */
	public String preCreateInventoryOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "preCreateOverflowOrder");

		HeadqInventoryFlowOrder order = formBean.getFlowOrder();
		order.setId(Common_util.ALL_RECORD_NEW);
		order.setType(HeadqInventoryFlowOrder.INVENTORY_ORDER);
		order.setStatus(HeadqInventoryFlowOrder.STATUS_INITIAL);
		flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, order);

		return "editInventoryOrder";
	}

	/**
	 * go to create 调货单 (inventory transfer order) 总部仓库调货暂时不管
	 * 
	 * @return
	 */
	public String preCreateInventoryTransferOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowJSPAction." + "preCreateOverflowOrder");

		HeadqInventoryFlowOrder order = formBean.getFlowOrder();

		ChainUtility.calculateParam(formBean, order);

		formBean.getFlowOrder().setType(HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER);

		flowService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, order);

		return "editInventoryTransferOrder";
	}

	/**
	 * 用户准备创建单据(创建报损单 报溢单)
	 * 
	 * @return
	 */
	public String preCreateInventoryFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction.preCreateInventoryFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		HeadqInventoryFlowOrder order = formBean.getFlowOrder();
		
		//prepare the 
		ChainUtility.calculateParam(formBean, order);
		
		flowService.prepareCreateFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);

		return "flowOrder";
	}
	

	/**
	 * 获取当前仓库的库存
	 * 
	 * @return
	 */
	public String getLevelOneCurrentInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - getLevelOneCurrentInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		headqInventoryService.prepareGetStoreInventoryRpt(formBean, uiBean);

		return "preInventoryRpt";
	}
	
	/**
	 * 获取当前仓库的库存
	 * 
	 * @return
	 */
	public String getInventoryChangeDetails() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - getInventoryChangeDetails");
		headqInventoryService.prepareGetStoreInventoryRpt(formBean, uiBean);

		return "inventoryChangeDetails";
	}



	/**
	 * 打开库存跟踪
	 * 
	 * @return
	 */
	public String openInvenTracePage() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - openInvenTracePage");
		Response response = headqInventoryService.getInventoryTraceInfor(formBean.getStoreId(), formBean.getPbId());
		if (response.getReturnCode() == Response.SUCCESS) {
			Map<String, List> data = (Map<String, List>) response.getReturnValue();
			List<HeadqInvenTraceInfoVO> traceVOs = data.get("rows");
			List<HeadqInvenTraceInfoVO> footers = data.get("footer");

			if (footers != null && footers.size() > 0)
				uiBean.setTraceFooter(footers.get(0));

			uiBean.setTraceItems(traceVOs);
		}
		return "OpenCheckInventoryTracePage";
	}

	/**
	 * 搜索库存类单据
	 * 
	 * @return
	 */
	public String selectInventoryFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preCreateInventoryFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		headqInventoryService.prepareSearchFlowOrderUI(formBean, uiBean, loginUserInfor);

		return "searchOrder";
	}

	/**
	 * to load the inventory flow order
	 * 
	 * @return
	 */
	public String loadOrder() {
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int orderId = formBean.getFlowOrder().getId();
		int orderStatus = 0;
		int orderType = 0;
		HeadqInventoryFlowOrder order = new HeadqInventoryFlowOrder();
		if (orderId == Common_util.ALL_RECORD_NEW) {
			order = formBean.getFlowOrder();
			orderStatus = formBean.getFlowOrder().getStatus();
			orderType = formBean.getFlowOrder().getType();
			formBean.setCanCancel(false);
			order = flowService.excludeUnqualified(order);
		}else if (orderId != Common_util.ALL_RECORD_NEW && formBean.getFlowOrder().getStatus() == BaseOrder.STATUS_DRAFT) {
			order = flowService.getOrderById(orderId, loginUserInfor);
			formBean.getFlowOrder().setStatus(BaseOrder.STATUS_DRAFT);
			formBean.setCanCancel(true);
			order = flowService.excludeUnqualified(order);
			orderStatus = order.getStatus();
			orderType = order.getType();
		}else {
			order = flowService.getOrderById(orderId, loginUserInfor);
			orderStatus = order.getStatus();
			orderType = order.getType();
			order.setStatusS(order.getStatusMaps().get(order.getStatus()));
		}

		//赋予按钮权限
		ChainUtility.calculateParam(formBean, order);

		//完成或者红冲单价
		

		if (orderStatus == HeadqInventoryFlowOrder.STATUS_COMPLETE || orderStatus == HeadqInventoryFlowOrder.STATUS_CANCEL) {
			flowService.prepareDisplayFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
			if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER)
				return "displayInventoryReport";
			else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER)
				return "displayInventoryTransferOrder";
			else
				return "displayFlowOrder";
		} else if (orderStatus == HeadqInventoryFlowOrder.STATUS_INITIAL || orderStatus == HeadqInventoryFlowOrder.STATUS_DRAFT) { //草稿单据

			if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER) {
				flowService.prepareCreateFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
				return "editInventoryOrder";
			} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
				flowService.prepareCreateInvenTransferOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
				return "editInventoryTransferOrder";
			} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_DRAFT) {//备注单据			
				formBean.setFlowOrder(order);
				uiBean.setStores(headqInventoryService.getHqAllStore());
				return "notesDocument";
			} else if (orderType == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER || orderType == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
				flowService.prepareCreateFlowOrderFormUIBean(loginUserInfor, uiBean, formBean, order);
				return "editFlowOrder";				
			} else {
				return ERROR;
			}
		} else {
			addActionError("你没有访问这个单据的权限");
			return ERROR;
		}

	}



	public String preSearchInvenFlowOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preSearchInvenFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		headqInventoryService.prepareSearchFlowOrderUI(formBean, uiBean, loginUserInfor);

		return "searchOrder";
	}

	/**
	 * to cancel the order 红冲单据
	 * 
	 * @return
	 */
	public String cancelOrder() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - cancelOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int orderId = formBean.getFlowOrder().getId();

		Response response = flowService.cancelOrder(orderId, loginUserInfor);
		if (response.getReturnCode() == Response.SUCCESS) {
			addActionMessage(response.getMessage());
			return preSearchInvenFlowOrder();
		} else {
			addActionError(response.getMessage());
			return loadOrder();
		}
	}

	/**
	 * 获取当前库存前，需要提前选择总部仓库
	 * 
	 * @return
	 */
	public String preGetCurrentInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preGetCurrentInventory");		
		headqInventoryService.initInventoryTracking(uiBean);
		return "inventoryStatistics";
	}
	
	/**
	 * 进入进销存变动统计
	 * 
	 * @returnf
	 */
	public String preGetInventoryChange() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - preGetInventoryChange");		
		headqInventoryService.initInventoryTracking(uiBean);
		
		return "inventoryChange";
	}
	
	/**
	 * 进入库存跟踪页面
	 * @return
	 */
	public String selectInventoryTracking() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - selectInventoryTracking");		

		headqInventoryService.initInventoryTracking(uiBean);
	
		return "inventoryTracking";
	}
	
	
	
	
	/**
	 * 进入总部库存备注单据页面
	 * @return
	 */
	public String selectNotesDocument() {
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info("HeadqInventoryFlowJSPAction - selectNotesDocument");
		Response response = new Response();

		try {
			response = headqInventoryService.getHqInventoryStores();

		} catch (Exception e) {
			loggerLocal.error(e);
			response.setQuickValue(Response.ERROR, response.getMessage());
		}
		List<HeadQInventoryStore> headStores = (List<HeadQInventoryStore>) response.getReturnValue();
		uiBean.setStores(headStores);
		initialzeFormBean(HeadqInventoryFlowOrder.INVENTORY_DRAFT,loginUserInfor);
		return "notesDocument";
	}
	
	public void initialzeFormBean(int orderType,UserInfor loginUserInfor) {
		HeadqInventoryFlowOrder flowOrder = new HeadqInventoryFlowOrder();
		flowOrder.setType(orderType);
		flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_INITIAL);
		flowOrder.setStatusS(flowOrder.getStatusMap().get(HeadqInventoryFlowOrder.STATUS_INITIAL));
		flowOrder.setCreator(loginUserInfor);
		flowOrder.setOrderDate(Common_util.getToday());
		formBean.setFlowOrder(flowOrder);
	}
	

	
	public String preInventoryRpt(){
		
		return "preInventoryRpt";
	}
	

	
	/**
	 * go to 报损单 (flow loss order)
	 */
	public String preCreateflowLossOrder(){
		UserInfor loginUser = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_CHAIN_USER);
		loggerLocal.info("HeadqInventoryFlowJSPAction.preCreateflowLossOrder");
    	
		HeadqInventoryFlowOrder order = formBean.getFlowOrder();
    	
		headqInventoryService.prepareCreateFlowOrderFormUIBean(loginUser, uiBean, formBean, order);
		
		//prepare the 
		ChainUtility.calculateParam(formBean, order);
		
		formBean.getFlowOrder().setType(ChainInventoryFlowOrder.FLOW_LOSS_ORDER);
		
		return "editFlowOrder";
	}
	

	
	

	
	/**
	 * 库存单-合并单据
	 * 
	 * @return
	 */
	public String mergeDocument() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(this.getClass().getName() + "." + "mergeDocument: " + formBean.getFlowOrder().getId());

		Response response = new Response();
		try {
			response = headqInventoryService.saveMergeDocument(formBean, loginUser);
		} catch (Exception e) {
			loggerLocal.error("ChainInventoryFlowAction.mergeDocument: " + loginUser.getUser_id());
			addActionError("合并单据发生系统错误，请联系系统管理员");
		}
		addActionMessage(response.getMessage());
		return preCreateInventoryOrder();
	}
	
	/**
	 * 总部/报损单/报溢单/调货单 保存草稿
	 * 
	 * @return
	 */
	public String saveToDraft() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowAction." + "saveToDraft ");
		Response response = new Response();
		try {
			response = flowService.saveToDraft(formBean.getFlowOrder(), formBean.getInventory(),formBean.getJsons(), loginUser);
			if (response.getReturnCode() == response.FAIL) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			} else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}
		return loadOrder();
	}
	
	/**
	 * 报损单，报溢单，调货单 单据过账
	 * 
	 * @return
	 */
	public String saveToFinal() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowAction." + "saveToFinal ");
		Response response = new Response();
		try {

			response = flowService.saveToFinal(formBean.getFlowOrder(),formBean.getInventory(),formBean.getJsons(), loginUser);
			if (response.getReturnCode() == response.FAIL) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			} else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveToFinal: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}
		return loadOrder();
	}
	
	
	/**
	 * 库存单刷新库存
	 * 
	 * @return
	 */
	public String refreshInventoryOrder() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "HeadqInventoryFlowAction." + "saveToFinal ");
		Response response = new Response();
		try {

			response = flowService.refreshInventoryOrder(formBean.getFlowOrder(),loginUser,formBean.getJsons());
			if (response.getReturnCode() == response.FAIL) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			} else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveToFinal: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("刷新错误，请联系管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}
		return loadOrder();
	}
	
	
	
		
	
	/**
	 * 总部库存盘点单保存草稿
	 * 
	 * @return
	 */
	public String saveInventoryToDraft() {
		UserInfor loginUser = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		loggerLocal.info(loginUser.getUser_name() + "headqInventoryFlowJSPAction." + "saveInventoryToDraft ");
		Response response = new Response();
		try {
			response = flowService.saveInventoryToDraft(formBean.getFlowOrder(), formBean.getInventory(), loginUser,formBean.getJsons());
			if (response.getReturnCode() == response.FAIL) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			} else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}
		} catch (Exception e) {
			loggerLocal.error("HeadqInventoryFlowAction.saveInventoryToDraft: " + loginUser.getUser_id());
			loggerLocal.info(formBean.getFlowOrder().toString());
			loggerLocal.error(e);
			response.setMessage("保存单据发生系统错误，请联系系统管理员");
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
		}
		return loadOrder();
	}
	

	
	
	
	/**
	 * 下载库存类单据明细
	 * @注意: HeadqInventoryFlowProducts 需要按数据库中插入的顺序降序取出 。原因： 这里的顺序是盘点扫描的顺序，打印公司货号的时候需要按顺序打印，否则贴条码时，无法按顺序找到白标
	 * @return
	 */
	public String downloadFlowOrder() {
		loggerLocal.info("headqInventoryFlowJSONAction - downloadFlowOrder");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		Response response = new Response();
		try {
			response = flowService.downloadFlowOrder(formBean.getFlowOrder().getId(), loginUserInfor);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return "error";
		}

		List<Object> values = (List<Object>) response.getReturnValue();

		formBean.setFileStream((InputStream) values.get(0));
		formBean.setFileName("zongbukucun--" + formBean.getFlowOrder().getId() + ".xls");

		return "download";
	}
	
	/**
	 * 下载总部商品库存跟踪记录信息
	 * 
	 * @return
	 */
	public String downloadStockHistory() {
		loggerLocal.info(this.getClass().getName() + ".downloadFinanceCategory");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			List<HeadqInvenTraceInfoVO> list = headqInventoryService.selectInventotyStocks(formBean.getStartDate(),formBean.getEndDate(),formBean.getStoreId(),
					formBean.getBarcode());
			response = headqInventoryService
					.generateStockExcel(contextPath + "WEB-INF\\template\\" + hqInventoryStockTemplate, list);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream);
			formBean.setFileName(hqInventoryStockTemplate);
			return "download";
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载库存报表
	 * 
	 * @return
	 */
	public String downloadHeadqInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - downloadHeadqInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Response response = new Response();
		try {
			response = headqInventoryService.generateInventoryExcelReport(formBean.getBelongTo(),formBean.getStoreId(), formBean.getYearId(),
					formBean.getQuarterId(), formBean.getBrandId(),formBean.getPbId(),
					contextPath + "WEB-INF\\template\\" + CHAIN_INVENTORY_REPORT_TEMPLATENAME,loginUserInfor);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream);
			formBean.setFileName(CHAIN_INVENTORY_REPORT_NAME);
			return "download";
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载库存报表
	 * 
	 * @return
	 */
	public String downloadChangeInventory() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - downloadHeadqInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Response response = new Response();
		try {
			response = headqInventoryService.getHeadqInventoryChangeDetails(formBean.getParentId(),formBean.getStartDate(),formBean.getEndDate(), formBean.getStoreIds(),
					formBean.getYearId(), formBean.getQuarterId(), formBean.getBrandId(), formBean.getCategoryLevelId(),
					formBean.getCategoryId(), formBean.getRptTypeId(), formBean.getBelongTo(),contextPath + "WEB-INF\\template\\" + INVENTORY_CHANGE_REPORT_DETAILS_TEMPLATENAME,loginUserInfor);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream);
			formBean.setFileName(CHAIN_INVENTORY_REPORT_NAME);
			return "download";
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载库存层级报表
	 * 
	 * @return
	 */
	public String downloadLevelReport() {
		loggerLocal.info("HeadqInventoryFlowJSPAction - downloadHeadqInventory");
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Response response = new Response();
		try {
			@SuppressWarnings("unchecked")
			List<HqInventoryChangeDetailsVO> list = (List<HqInventoryChangeDetailsVO>) headqInventoryService.getHeadqInventoryChangeDetails(formBean.getParentId(),formBean.getStartDate(),formBean.getEndDate(), formBean.getStoreIds(),
					formBean.getYearId(), formBean.getQuarterId(), formBean.getBrandId(), formBean.getCategoryLevelId(),
					formBean.getCategoryId(), formBean.getRptTypeId(), formBean.getBelongTo(),loginUserInfor).getReturnValue();
			response = headqInventoryService.getHeadqInventoryLevelReport(list,formBean.getStoreIds(),contextPath + "WEB-INF\\template\\" + INVENTORY_CHANGE_REPORT_TEMPLATENAME);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream);
			formBean.setFileName(CHAIN_INVENTORY_REPORT_NAME);
			return "download";
		} else
			return ERROR;
	}

}


